const redis = require('../db/redis')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { login } = require('../controller/user')

const handleUserRouter = (req, res) => {
  // 登录
  if (req.method === 'POST' && req.path === '/api/user/login') {
    const username = req.body.username || ''
    const password = req.body.password | ''

    return login(username, password).then(data => {
      if(data.username) {
        // 用户登录成功，设置session
        req.session.username = data.username
        req.session.realname = data.realname
        // 同步到 redis
        redis.set(req.sessionId, req.session)

        return new SuccessModel(data)
      } else {
        return new ErrorModel('登录失败')
      }
    })
  }
  console.log(req.method, req.path)
  if (req.method === 'GET' && req.path === '/api/user/login-test') {
    console.log('req.session', req.session)
    if(req.session.username) {
      return Promise.resolve(new SuccessModel(req.session))
    } else {
      return Promise.resolve(new ErrorModel('您未登录，请先登录'))
    }
  }

}

module.exports = handleUserRouter